package com.fuyun.rpc.server;

import com.fuyun.rpc.common.serializer.Serializer;
import com.fuyun.rpc.common.serializer.SerializerFactory;
import com.fuyun.rpc.server.config.RegistryConfig;
import com.fuyun.rpc.server.config.RpcConfig;
import com.fuyun.rpc.server.protocol.*;
import com.fuyun.rpc.server.registry.LocalRegistry;
import com.fuyun.rpc.server.registry.Registry;
import com.fuyun.rpc.server.registry.RegistryFactory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: zrq1351
 * @date: 2025/2/14
 */
@Slf4j
@Data
public class RpcApplication {

	private RpcConfig rpcConfig;
	private RegistryConfig registryConfig;

	public RpcApplication(RpcConfig rpcConfig, RegistryConfig registryConfig) {
		this.rpcConfig = rpcConfig;
		this.registryConfig = registryConfig;
	}

	/**
	 * 初始化FuYun-RPC框架 该方法负责启动注册中心和服务器，以及序列化器的初始化，并在JVM关闭时添加钩子进行清理工作
	 */
	public void init() {
		Registry registry = RegistryFactory.getInstance(rpcConfig.getRegistry());
		log.info("fuyun-rpc初始化, rpcConfig = {}, registryConfig = {}", rpcConfig, registryConfig);
		registry.init(registryConfig);
		Server server = ServerFactory.getInstance(rpcConfig.getProtocol());
		Serializer serializer = SerializerFactory.getInstance(rpcConfig.getSerializer());
		if (server instanceof VertxHttpServer) {
			server.start(rpcConfig.getServerPort(), new VertxHttpServerHandler(serializer, rpcConfig));
		} else if (server instanceof VertxTcpServer) {
			server.start(rpcConfig.getServerPort(), new VertxTcpServerHandler(serializer, rpcConfig));
		}
		Runtime.getRuntime()
			.addShutdownHook(new Thread(() -> {
				LocalRegistry.clear();
				registry.destroy();
				log.info("registry destroy");
			}));
	}

}